import './index.less'
import React, { useContext, useEffect, useRef, useState } from 'react';
import type { InputRef, DatePickerProps } from 'antd';
import { Button, DatePicker, Form, Input, Popconfirm, Table, Select, Typography, Modal, Tabs } from 'antd';
import type { FormInstance } from 'antd/es/form';
import dayjs from 'dayjs';
import locale from 'antd/es/date-picker/locale/en_US';
import { From, Public } from '..';
import { Outlet } from '@/.umi/exports';
import { CalendarOutlined } from '@ant-design/icons';
import type { TabsProps } from 'antd';
import { Bookkeeping, cashData, cashDataDel, book1, model, exports,editCash } from '@/services/financialApi';
import { number } from 'echarts';
const { Text } = Typography;
const EditableContext = React.createContext<FormInstance<any> | null>(null);
const time2string = (time: any) => {
    let time1 = time.split(' ')
    let yun = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
    let montn
    yun.forEach((v, i) => {
        if (time1[1] == v) {
            montn = i + 1
        }
    })
    return time1[3] + '-' + montn + '-' + time1[2];
}
interface Item {
    key: string;
    remark: string;
    date: string;
    pay: number;
    notes: string;
    income: number;
    billNum: string;
    cusName: string;
    balance: number;
    catName: string;
    billingMethod: string
}

interface EditableRowProps {
    index: number;
}

const EditableRow: React.FC<EditableRowProps> = ({ index, ...props }) => {
    const [form] = Form.useForm();
    return (
        <Form form={form} component={false}>
            <EditableContext.Provider value={form}>
                <tr {...props} />
            </EditableContext.Provider>
        </Form>
    );
};

interface EditableCellProps {
    title: React.ReactNode;
    editable: boolean;
    editBalance: boolean;
    children: React.ReactNode;
    dataIndex: keyof Item;
    record: Item;
    handleSave: (record: Item) => void;
}

type EditableTableProps = Parameters<typeof Table>[0];

interface DataType {
    key?: React.Key;
    docNum: string;
    remark: any;
    notes: any
    date: any;
    pay: any;
    income: any;
    billNum: any;
    cusName: any;
    catName: any;
    balance: number;
    billingMethod: any
}
type ColumnTypes = Exclude<EditableTableProps['columns'], undefined>;
const Cash = () => {
    const searchParams = new URLSearchParams(location.search);
    const id = Number(searchParams.get('id'))
    const [pageNo, setPageNo] = useState(1)
    let [va1, setVa1] = useState(1)
    let va2: string
    let begin = '2023-09-06'
    let end = '2023-10-06'
    let num = 1
    // 表格数据
    const [dataSource, setDataSource] = useState<DataType[]>([]);
    // 请求数据
    const datas = () => {
        cashData({ accId: va1, dueDate: end, pageNo: pageNo, sobId: 1, startDate: begin }).then(({ data }) => {
            console.log(data, 1)
            let _data: any = data.list.map((v: any) => ({ ...v, date: time2string(String(new Date(v.date))), docNum: v.docNum + '-' + num++, }))
            setDataSource(_data)
        })
    }
    // 记账类别数据
    let [Bookkeep, setBookkeep] = useState<any>([])
    useEffect(() => {
        if (id != null) {
            Bookkeeping(id).then((res) => {
                let lwyHome = []
                for (let i = 0; i < res.data.length; i++) {
                    let n: any = {}
                    n.value = res.data[i].accId
                    n.label = res.data[i].accNumName
                    lwyHome.push(n)
                }
                setBookkeep(lwyHome)
            })
        }

        datas()
    }, [])

    // 弹框
    const [isModalOpen, setIsModalOpen] = useState(false);
    const showModal = () => {
        setIsModalOpen(true);
    };
    const handleOk = () => {
        setIsModalOpen(false);
    };
    const handleCancel = () => {
        setIsModalOpen(false);
    };
    // 弹框表格数据
    const columns1 = [
        {
            title: '编号',
            dataIndex: 'name',
        },
        {
            title: '名称',
            dataIndex: 'age',
        },
    ];
    const data = [
        {
            key: '1',
            name: 'John Brown',
            age: 32,
            address: 'New York No. 1 Lake Park',
        },
        {
            key: '2',
            name: 'Jim Green',
            age: 42,
            address: 'London No. 1 Lake Park',
        },
        {
            key: '3',
            name: 'Joe Black',
            age: 32,
            address: 'Sydney No. 1 Lake Park',
        },
    ];
    // 选项卡
    const items: TabsProps['items'] = [
        {
            key: '1',
            label: '客户',
            children: <Table columns={columns1} dataSource={data} size="middle" />,
        },
        {
            key: '2',
            label: '供应商',
            children: 'Content of Tab Pane 2',
        },
    ];
    const onChange = (key: string) => {
        console.log(key);
    };
    // 可编辑单元格操作
    const [date0, setDate0] = useState('')
    const [record1,setRecord1]=useState({})
    const EditableCell: React.FC<EditableCellProps> = ({
        title,
        editable,
        children,
        dataIndex,
        editBalance,
        record,
        handleSave,
        ...restProps
    }) => {

        const [editing, setEditing] = useState(false);
        const [editing2, setEditing2] = useState(false);
        const [editing3, setEditing3] = useState(false);
        const [editing4, setEditing4] = useState(false);
        const inputRef = useRef<InputRef>(null);
        const selRef = useRef<InputRef>(null);
        const pickRef = useRef<InputRef>(null);
        const form = useContext(EditableContext)!;
        const [hhh, sethhh] = useState('')
        type PickerType = 'time' | 'date';
        const [type, setType] = useState<PickerType>('time');
        useEffect(() => {
            if (editing) {
                if (record.jouId != 0 && title == '余额') {
                } else {
                    inputRef.current!.focus();
                }
            }
        }, [editing]);
        const toggleEdit = () => {
            if (dataIndex == 'remark' || dataIndex == 'pay' || dataIndex == 'income' || dataIndex == 'billNum' || dataIndex == 'notes' || dataIndex == 'balance') {
                setEditing(!editing);
            } else if (dataIndex == 'date') {
                setEditing2(!editing2);
            } else if (dataIndex == 'catName' || dataIndex == 'billingMethod') {
                setEditing3(!editing3);
            } else if (dataIndex == 'cusName') {
                setEditing4(!editing4);
            }

            if (dataIndex == 'date') {
                form.setFieldsValue({ ...record, [dataIndex]: dayjs(record[dataIndex], 'YYYY-MM-DD') });
            } else {
                form.setFieldsValue({ ...record, [dataIndex]: record[dataIndex] });
            }


        };

        const save = async () => {
            let r
            try {
                const values = await form.validateFields();
                if (values.age) {
                    values.age = time2string(String(values.age.$d))
                }
                toggleEdit();
                handleSave({ ...record, ...values});
                r={ ...record, ...values,accId:va1}
               
                setRecord1(r)
                console.log(r,1);
                
            } catch (errInfo) {
                console.log('Save failed:', errInfo);
            }
            editCash(r).then((res)=>{
                datas()
            })
        };
       
        let childNode = children;
        if (editable) {

            if (editing) {
                if (record.jouId != 0 && title == '余额') {
                    childNode = <div>{children}</div>
                } else {
                    childNode = <Form.Item
                        style={{ margin: 0 }}
                        name={dataIndex}
                    >
                        <Input ref={inputRef} onPressEnter={save} onBlur={save} />
                    </Form.Item>
                }
            } else if (editing2) {
                childNode = <Form.Item

                    style={{ margin: 0 }}
                    name={dataIndex}
                >
                    <DatePicker onBlur={save}  locale={locale} style={{ width: 200 }} onChange={date6} value={dayjs(date0)} />
                </Form.Item>
            } else if (editing3) {
                childNode = <Form.Item
                    style={{ margin: 0 }}
                    name={dataIndex}
                ><Select onBlur={save}
                    style={{ width: 120 }}
                    options={[
                        { value: 'aaa', label: 'aaa' },
                        { value: 'bbb', label: 'bbb' },
                        { value: 'ccc', label: 'ccc' },
                        { value: 'ddd', label: 'ddd' },
                    ]}
                    />
                </Form.Item>
            } else if (editing4) {
                childNode = <Form.Item
                    style={{ margin: 0 }}
                    name={dataIndex}>
                    <Button onClick={showModal}>
                        <CalendarOutlined />
                    </Button>
                    <Modal title="选择往来单位" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
                        <Tabs defaultActiveKey="1" items={items} onChange={onChange} />;
                    </Modal>
                </Form.Item>
            } else {

                childNode = <div className="editable-cell-value-wrap" style={{ paddingRight: 24 }} onClick={toggleEdit}>
                    {children}
                </div>
            }
        }
        return <td {...restProps}>{childNode}</td>;
    };

    const date6 = (v: any) => {
        setDate0(time2string(String(v.$d)))
    }
    const [count, setCount] = useState(2);
    // 删除
    const handleDelete = (id: number) => {
        cashDataDel(id).then((res) => {
            console.log(res);
            datas()
        })
    };
    // 搜索
    let [Bookkeep1, setBookkeep1] = useState<any>([])
    const handleChange = (value: number) => {
        // 收支类别的数据
        setVa1(value)
        book1(value).then((res) => {
            let lwyHome = []
            for (let i = 0; i < res.data.length; i++) {
                let n: any = {}
                n.value = res.data[i]
                n.label = res.data[i]
                lwyHome.push(n)
            }
            setBookkeep1(lwyHome)
        })
    }
    // 时间
    const handleChange1 = (v: string, v1: string) => {
        begin = v1[0]
        end = v1[1]
    }
    // 收支类别
    const handleChange2 = (v: string) => {
        va2 = v
    }
    // 搜索
    const search = () => {
        datas()
    }
    const defaultColumns: (ColumnTypes[number] & { editable?: boolean; dataIndex: string })[] = [
        {
            title: '单据编号',
            dataIndex: 'docNum',
            width: '30%',
            // editable: true,
        },
        {
            title: '日期',
            dataIndex: 'date',
            editable: true,
        },
        {
            title: '摘要',
            dataIndex: 'remark',
            width: '30%',
            editable: true,
        },
        {
            title: '收支类别',
            dataIndex: 'catName',
            editable: true,
        },
        {
            title: '收入(借方)',
            dataIndex: 'income',
            width: '30%',
            editable: true,
        },
        {
            title: '支出(贷方)',
            dataIndex: 'pay',
            width: '30%',
            editable: true,
        },
        {
            title: '余额',
            dataIndex: 'balance',
            width: '30%',
            editable: true,
        },
        {
            title: '关联凭证',
            dataIndex: 'associatedVouchers',
            width: '30%',
            render: (text) => <a>{text}</a>
        },
        {
            title: '来往单位',
            dataIndex: 'cusName',
            width: '30%',
            editable: true,
        },
        {
            title: '结算方式',
            dataIndex: 'billingMethod',
            editable: true,
        },
        {
            title: '票据号',
            dataIndex: 'billNum',
            width: '30%',
            editable: true,
        },
        {
            title: '备注',
            dataIndex: 'notes',
            width: '30%',
            editable: true,
        },
        {
            title: 'operation',
            dataIndex: 'operation',
            render: (_, record: any) => {
                if (record.jou_id != 0) {
                    return <>
                        <a onClick={() => handleAdd(record)}>下方添加</a>
                        <Popconfirm title="Sure to delete?" onConfirm={() => handleDelete(record.jou_id)}>
                            <a>删除</a>
                        </Popconfirm>
                        <a>打印</a>
                    </>
                }

            }
        },
    ];
    // 新增单元格
    // 数据
    const [input1, setInput1] = useState('')
    const inputs = (e: any) => {
        console.log(e, 2);
    }
    // const date5=(v:any)=>{
    //     console.log(v,9);

    // }
    const date5: DatePickerProps['onChange'] = (date, dateString) => {
        console.log(date, dateString, 9);
    };
    const handleAdd = (record: { [props: string]: any }) => {
        console.log(dataSource, 3);
        let date1 = new Date()
        let date2 = time2string(String(date1))
        let date3 = date2.split('-')
        let date4 = date3[0] + date3[1] + date3[2]
        num = record.docNum.split('-')[3]

        const newData: DataType = {
            docNum: '1-1001-' + date4 + '-' + ++num,
            remark: <Input onChange={inputs} value={input1} />,
            notes: '',
            date: <DatePicker style={{ width: 200 }} defaultValue={dayjs(new Date())} onChange={date5} format="YYYY-MM-DD" />,
            pay: <Input />,
            income: <Input />,
            billNum: '',
            balance: record.balance,
            catName: <Select
                style={{ width: 120 }}
                options={[
                    { value: 'aaa', label: 'aaa' },
                    { value: 'bbb', label: 'bbb' },
                    { value: 'ccc', label: 'ccc' },
                    { value: 'ddd', label: 'ddd' },
                ]}
            />,
            cusName: <Form.Item
                style={{ margin: 0 }}
            >
                <Button onClick={showModal}>
                    <CalendarOutlined />
                </Button>
                <Modal title="选择往来单位" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
                    <Tabs defaultActiveKey="1" items={items} onChange={onChange} />;
                </Modal>
            </Form.Item>,
            billingMethod: <Select
                style={{ width: 120 }}
                options={[
                    { value: 'aaa', label: 'aaa' },
                    { value: 'bbb', label: 'bbb' },
                    { value: 'ccc', label: 'ccc' },
                    { value: 'ddd', label: 'ddd' },
                ]}
            />
        };
        setDataSource([...dataSource, newData]);
        setCount(count + 1);
    };

    const handleSave = (row: DataType) => {
        const newData = [...dataSource];
        const index = newData.findIndex((item) => row.key === item.key);
        const item = newData[index];
        newData.splice(index, 1, {
            ...item,
            ...row,
        });
        console.log(newData, 4);

        setDataSource(newData);
    };

    const components = {
        body: {
            row: EditableRow,
            cell: EditableCell,
        },
    };

    const columns = defaultColumns.map((col) => {
        if (!col.editable) {
            return col;
        }
        return {
            ...col,
            onCell: (record: DataType) => ({
                record,
                editable: col.editable,
                dataIndex: col.dataIndex,
                title: col.title,
                handleSave,
            }),
        };
    });
    // 分页
    const pageS = (page: number) => {
        setPageNo(page)
    }
    // 导出
    const exprots = () => {
        exports({ accId: va1, dueDate: end, sobId: 1, startDate: begin }).then((res) => {
            let a = document.createElement('a')
            let b = new Blob([res], { type: '.xls' })
            a.setAttribute('href', URL.createObjectURL(b))
            a.setAttribute('download', '财务.xls')
            a.click()
        })
    }
    return <div>
        <Public header='现金日记账'></Public>
        {/* 操作和搜索框 */}
        <From type='记账方式' Bookkeep={Bookkeep} Bookkeep1={Bookkeep1} handleChange1={handleChange} search={search} handleChange2={handleChange1} handleChange3={handleChange2} id={id} exprots={exprots}></From>
        {/* 表格 */}
        <Table style={{ width: '98%', margin: 'auto', marginTop: 20 }}
            pagination={{ current: pageNo, onChange: pageS }}
            components={components}
            rowClassName={() => 'editable-row'}
            bordered
            dataSource={dataSource}
            columns={columns as ColumnTypes}
            summary={(data) => {
                let ages = 0;
                let repayments = 0;
                let bal;
                if (data[(data.length - 1)] != undefined) {
                    bal = data[(data.length - 1)].balance
                }

                data.forEach(({ income, pay }) => {
                    if (income != null && pay != null) {
                        ages += income
                        repayments += pay
                    }

                })
                return (<>
                    <Table.Summary.Row>
                        <Table.Summary.Cell colSpan={4} index={0} className="total-cell">总计:</Table.Summary.Cell>
                        <Table.Summary.Cell colSpan={1} index={1}>
                            <Text>{ages}</Text>
                        </Table.Summary.Cell>
                        <Table.Summary.Cell colSpan={1} index={1}>
                            <Text>{repayments}</Text>
                        </Table.Summary.Cell>
                        <Table.Summary.Cell colSpan={1} index={1}>
                            <Text>{bal}</Text>
                        </Table.Summary.Cell>
                        <Table.Summary.Cell index={1} colSpan={6} />
                    </Table.Summary.Row>
                </>
                )
            }} />
        <Outlet />
    </div>
}
export default Cash

